<?php
defined('BASEPATH') OR exit('No direct script access allowed');


class Wechat extends CI_Controller
{
    public $host = "http://class.sise.com.cn:7001/sise/";
    public $main_url = "http://class.sise.com.cn:7001/sise/module/student_states/student_select_class/main.jsp";
    public $post_url = 'http://class.sise.com.cn:7001/sise/login_check.jsp';


    public function index(){
        if (!isset($_GET['echostr'])) {
            $this->responseMsg();
        }else{
            $this->valid();
        }

    }
    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "Bill_wechat";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }


        //响应消息
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            //var_dump($postObj);
            /*返回的结果应该是
            object(SimpleXMLElement)#1 (4)
                {
                    ["toUserName"]=> string(4) "***"
                    ["fromUsername"]=> string(4) "***"
                    ["MsgType"]=> string(8) "***"
        
                }等等*/
            $RX_TYPE = trim($postObj->MsgType);
             
            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            echo $result;
        }else {
            echo "随便输入点什么吧";
            exit;
        }
    }

    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注,回复绑定也可以进行绑定";
                break;
           
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "course":
                        $content = $this->course($object->FromUserName);
                        break;
                    case "info":
                        $content = $this->StuInfo($object->FromUserName);
                        break;
                    case "kaoqin":
                        $content = $this->Stukaoqin($object->FromUserName);
                        break;
                    case "reward":
                        $content = $this->Stureward($object->FromUserName);
                        break;
                    case "score":
                        $content = $this->StuScore($object->FromUserName);
                        break;
                    case "illegal":
                        $content = $this->Stuillegal($object->FromUserName);
                        break;
                    case "time":
                        $content = $this->StuExamTime($object->FromUserName);
                        break;
                    case 'unbind':
                        $content = $this->StuUnbind($object->FromUserName);
                        break;
                    case 'bind' :
                        $content = "<a href='http://mysise.duapp.com/index.php/binduser/index/".$object->FromUserName."'>点我绑定</a>";
                        break;

                   
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;
                }
                break;
            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
                
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        if(is_array($content)){
                $result = $this->transmitNews($object, $content);
        }else{
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }


    public function receiveText($object=null)
    {

        $keyword = trim($object->Content);
        if (strstr($keyword, "考勤")){
            $content = $this->Stukaoqin($object->FromUserName);
        }elseif(strstr($keyword, "成绩")){
            $content = $this->StuScore($object->FromUserName);
        }elseif(strstr($keyword, "个人信息")){
            $content = $this->StuInfo($object->FromUserName);
        }elseif(strstr($keyword, "考试时间")){
            $content = $this->StuExamTime($object->FromUserName);
        }elseif(strstr($keyword, "奖励")){
            $content = $this->Stureward($object->FromUserName);
        }elseif (strstr($keyword, "绑定")) {
            // $content = "http://mysise.duapp.com/index.php/binduser/index/".$object->FromUserName."";  
            $content = "<a href='http://mysise.duapp.com/index.php/binduser/index/".$object->FromUserName."'>点我绑定</a>"; 
        }elseif (strstr($keyword, "没事")) {
            $content = "http://mysise.duapp.com/index.php/welcome/testclose";   
        }elseif (strstr($keyword, "课程")){
            $content = $this->course($object->FromUserName);
        }elseif(strstr($keyword, "违规记录")){
            $content = $this->Stuillegal($object->FromUserName);
            
        }
        if(is_array($content)){
            $result = $this->transmitNews($object, $content);
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }
    public function transmitText($object, $content)
    {
        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

        //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
        </item>";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>%s</ArticleCount>
        <Articles>
        $item_str</Articles>
        </xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    public function test(){
        $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/kaoqin");
        $data = json_decode($data,TRUE);
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }


    //课程
    public function course($id){
        $CourseNew = "";
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/course/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
             $dayArr = array(
                '星期一',
                '星期二',
                '星期三',
                '星期四',
                '星期五',
                '星期六',
                '星期天'
            );
            $time = array(
                '9:00-10:20',
                '10:40-12:00',
                '12:00-13:40',
                '14:00-15:20',
                '15:30-16:50',
                '17:00-18:20',
                '19:00-20:20',
                '20:30-21:50'

                );
            $day = "";
            $CourseNew = "---------".$data['week']."-----------\n";
            preg_match('/\d+/i', $data['week'],$week);
            foreach ($dayArr as $key=> $item) {
                if($item == $data['day'])
                    $day = $key;      
            }
            for($i=0; $i<8; $i++){
                if($data['course'][$i*7+$day] != "&nbsp;")
                {
                    preg_match('/\((.+)\[/i', $data['course'][$i*7+$day],$count_week);
                    preg_match_all('/\d+/i', $count_week[1],$week_match);
                    //var_dump($room);
                    if((int)$week[0]<=(int)$week_match[0][count($week_match[0])-1] && (int)$week[0]>=(int)$week_match[0][0]){
                        preg_match('/\[.*\]/i', $data['course'][$i*7+$day],$room);
                        
                       $course = preg_replace('/\(.*\)/i', " ", $data['course'][$i*7+$day]);
                        $CourseNew .= "课程名:".$course."\n课室:".$room[0]."\n时间:".$time[$i]."\n\n";
                    }
                }
            }
            $content = array();
            $content[] = array("Title"=>"今天课表",  "Description"=>$CourseNew, "PicUrl"=>"http://www.cnsc8.com/res/tupian_201401/Big_Pic/DtkLhDKvrk.jpg", "Url" =>"http://mysise.duapp.com/index.php/getcourse/index/".$id."");
        }else{
            $content = "未绑定,无法使用该功能";
        }
        return $content;
    }

    //个人信息
    public function StuInfo($id){
        $content = "";
        $PersonArr = array(
            '学号',
            '姓名',
            '年级',
            '专业',
            '身份证',
            '电子邮件',
            '导师',
            '辅导员',
            '班级'
            );
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/score/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
            foreach ($data['info'] as $PersonKey => $Person) {
                $content.= $PersonArr[$PersonKey].":".$Person."\n";   
            }
        }else{
            $content = "你还没进行绑定,无法使用查询个人信息功能"; 
        }
        return $content;
    }

    //考勤
    public function Stukaoqin($id){
        $content = "";
        $student = $this->student_model->get_student($id);
        //$content = $student[0]['sid']."----".$student[0]['password'];
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/kaoqin/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
            foreach ($data as $Attendance) {
                $content.="课程: ".$Attendance['1']."\n状态: ".trim(strip_tags($Attendance['2']))."\n\n";
            }
        }else{
            $content = "你还没进行绑定,无法使用考勤功能";
        }
        return $content;
    }

    //奖励与惩罚
    public function Stureward($id){
        $content = "";
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/reward/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
            foreach ($data as $reward_status => $status) {
                if($reward_status == 0){
                    $content.="-------奖励情况-----\n";
                    if(!empty($status[0])){
                        foreach ($status as $Reward_data) {
                            $content.="学年:".$Reward_data[0]." ".$Reward_data[1]."\n奖励级别:".$Reward_data[2]."\n原因:".$Reward_data[3]."\n日期:".$Reward_data[5]."\n\n";
                        }
                    }else{
                        $content.= "无";
                    }
                }else{
                    $content.="\n-------惩罚情况-----\n";
                    if(!empty($status[0])){
                        foreach ($status as $Punish_data) {
                            $content.="学年:".$Punish_data[0]." ".$Punish_data[1]."\n 奖励级别:".$Punish_data[2]."\n原因:".$Punish_data[3]."\n日期:".$Punish_data[5]."\n";
                        }
                    }else{
                        $content .= "无";
                    }
                }
            }
        }else{
            $content = "你还没进行绑定,无法使用该功能";
        }

        return $content;
    }


    //成绩
    public function StuScore($id){
        $ScoreInfo = $this->config->item('year');
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/score/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
            foreach ($data['score'] as $score) {
                if (isset($score[8])) {
                    if($score[6] == $this->config->item('year')){
                    $ScoreInfo.="\n课程名:".$score[1]."\n成绩:".$score[7]."\n";
                    }
                }
                
            }
            $content = array();
            $content[] = array("Title"=>"成绩",  "Description"=>$ScoreInfo, "PicUrl"=>"http://img2.3lian.com/2014/c7/29/d/23.jpg", "Url" =>"http://mysise.duapp.com/index.php/getcourse/scorehtml/".$id."");
        }else{
           $content = "你还没进行绑定,无法使用查询成绩功能"; 
        }
        return $content;
    }

    //违规记录
    public function Stuillegal($id){
        $content = "违规记录\n";
        $ForField = array(
                '学年:',
                '学期:',
                '宿舍:',
                '停电日期:',
                '停电次数:',
                '停电天数:',
                '停电原因:',
                '责任人:'
            );
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/illegal/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE); 
            if($data['msg'] == "success"){
                if(!empty($data['illegal'])){
                    foreach ($data['illegal'][0] as $key => $value) {
                        $content.= $ForField[$key]." ".$value."\n";
                    }
                }else{
                    $content.= "无";
                }
            }else{
                $content = "sorry,服务器错误...";
            }
        }else{
            $content = "未绑定,无法使用该功能";
        }

        return $content;
    }

    //考试时间
    public function StuExamTime($id){
        $content = "";
        $TimeInfo = array(
                '课程名称',
                '时间',
                '考场',
                '座位'
            );
        $student = $this->student_model->get_student($id);
        if($student){
            $data = file_get_contents("http://114.215.88.72/newmysise1/wechat/exam_time/".$student[0]['sid']."/".$student[0]['password']);
            $data = json_decode($data,TRUE);
            foreach ($data as $examKey => $examTime) {
                // $content.=$examTime[1]."----".$examTime[2]."----".$examTime[3]."----".$examTime[5]."\n";
                $content.= "<".$examKey.">\n";
                $content.= "课程: ".$examTime[1]."\n时间: ".$examTime[2]."\n      \t".$examTime[3]."\n考场: ".$examTime[4]."\n座位: ".$examTime[6]."\n\n";
            }
        }else{
            $content = "你还没进行绑定,无法使用查询考试时间功能";
        }
        return $content;
    }

        //解除绑定
    public function StuUnbind($id){
        $student = $this->student_model->get_student($id);
        if($student){
            $this->student_model->del($id);
            $content = "解除绑定成功，";
        }else{
            $content = "你都没绑定，还解绑？？";
        }
        return $content;
    }


}